/*************************************************************************
	> File Name: binarytree.c
	> Author: Wang Bo
	> Mail: 1276106221@qq.com
	> Created Time: 2020年12月03日 星期四 19时56分14秒
 ************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include "binarytree.h"

BSTree *getNewTree() {
    BSTree *t = (BSTree *)malloc(sizeof(BSTree));
    t->root = NULL;
    t->cnt = 0;
    return t;
}

Node *getNewTreeNode(int val) {
    Node *n = (Node *)malloc(sizeof(Node));
    n->lchild = NULL;
    n->rchild = NULL;
    n->data = val;
    return n;
}

Node *insertTreeNode(Node *root, int val, int *f) {
    if (root == NULL) {
        *f = 1;
        return getNewTreeNode(val);
    }
    if (root->data == val) return root;
    if (val > root->data) {
        root->rchild = insertTreeNode(root->rchild, val, f);
    } else {
        root->lchild = insertTreeNode(root->lchild, val, f);
    }
    return root;
}

void insertRoot(BSTree *t, int val) {
    if (t == NULL) return ;
    int f = 0;
    t->root = insertTreeNode(t->root, val, &f);
    t->cnt += f;
    return ;
}

void clearTreeNode(Node *root) {
    if (root == NULL) return ;
    clearTreeNode(root->lchild);
    clearTreeNode(root->rchild);
    free(root);
    return ;
}

void clearTree(BSTree *t) {
    if (t == NULL) return ;
    clearTreeNode(t->root);
    free(t);
    return ;
}

void generalize(BSTree *t) {
    if (t == NULL) return ;
    printf("二叉树(节点数: %d)的广义表：", t->cnt);
    genPrint(t->root);
    printf("\n");
    return ;
}

void genPrint(Node *root) {
    if (root == NULL) return ;
    printf("%d", root->data);
    if (root->lchild == NULL && root->rchild == NULL) return ;
    printf("(");
    genPrint(root->lchild);
    printf(",");
    genPrint(root->rchild);
    printf(")");
    return ;
}
